package com.ja.openchat.ui.found;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.widget.Toolbar;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.ja.openchat.BR;
import com.ja.openchat.R;
import com.ja.openchat.adapters.UserGridAdapter;
import com.ja.openchat.ui.base.JaBaseActivity;
import com.ja.openchat.ui.chat.MobileContactHomeActivity;
import com.ja.openchat.ui.contact.ContactDetailActivity;
import com.ja.openchat.ui.me.PersonalDataFragment;
import com.zy.openchat.core.model.circle.UserTags;
import com.zy.openchat.core.model.user.UserInfo;
import com.zy.openchat.util.Common;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;

import butterknife.BindView;

public class UserTagsActivity extends JaBaseActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    @BindView(R.id.et_name)
    EditText et_name;
    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.tv_ok_right)
    TextView tv_ok_right;
    private UserGridAdapter userGridAdapter;

    public static void createTag(Activity context, int requestCode, ArrayList<UserInfo> userInfos, int type) {
        Intent intent = new Intent(context, UserTagsActivity.class);
        if (userInfos != null) {
            intent.putExtra("users", userInfos);
        }
        intent.putExtra("type", type);
        context.startActivityForResult(intent, requestCode);
    }

    public static void editTag(Activity context, int requestCode, UserTags userTags, int type) {
        if (userTags == null) {
            return;
        }
        Intent intent = new Intent(context, UserTagsActivity.class);
        intent.putExtra("usertag", userTags);
        intent.putExtra("type", type);
        context.startActivityForResult(intent, requestCode);
    }

    private ArrayList<UserInfo> membersList;

    private UserInfo addUserInfo;

    private UserInfo getAddUserInfo() {
        if (addUserInfo == null) {
            addUserInfo = new UserInfo();
            addUserInfo.id = -1;
        }
        return addUserInfo;
    }

    private int tagType = 0;
    private UserTags mUserTags;

    @Override
    public void setStatusBar() {
        BarUtils.setStatusBarColor(this, ContextCompat.getColor(this,R.color.BG));
        BarUtils.setStatusBarLightMode(this, true);
        BarUtils.addMarginTopEqualStatusBarHeight(binding.getRoot());
    }

    @Override
    public void initData() {
        toolbar.setBackground(ContextCompat.getDrawable(this, R.drawable.transparent_shape));
        if (getIntent() != null) {
            tagType = getIntent().getIntExtra("type", 0);
            if (getIntent().getSerializableExtra("users") != null) {
                membersList = (ArrayList<UserInfo>) getIntent().getSerializableExtra("users");
            }
            if (getIntent().getParcelableExtra("usertag") != null) {
                mUserTags = getIntent().getParcelableExtra("usertag");
                if (!Common.isEmpty(mUserTags.users)) {
                    membersList = new ArrayList<>();
                    for (long userId : mUserTags.users) {
                        UserInfo userInfo = UserInfo.getUserInfo(userId);
                        if (userInfo != null) {
                            membersList.add(userInfo);
                        } else {
                            UserInfo userInfo1 = new UserInfo();
                            userInfo1.id = userId;
                            membersList.add(userInfo1);
                        }
                    }
                }
            }
        }
        if (mUserTags != null) {
            et_name.setText(mUserTags.name);
        }
        if (membersList == null) {
            membersList = new ArrayList<>();
        }
        membersList.add(getAddUserInfo());
//        UserInfo deleteUser = new UserInfo();
//        deleteUser.id = -2;
//        membersList.add(deleteUser);

        setTitle(getString(R.string.save_as_label));
        tv_ok_right.setVisibility(View.VISIBLE);
        tv_ok_right.setText(getString(R.string.save_text));
        tv_ok_right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (membersList == null || membersList.size() <= 1) {
                    ToastUtils.showShort(getString(R.string.please_add_user));
                    return;
                }
                if (TextUtils.isEmpty(et_name.getText())) {
                    ToastUtils.showShort(getString(R.string.please_fill_name));
                    return;
                }
                membersList.remove(getAddUserInfo());
                showProgress();
                if (mUserTags == null) {
                    UserCircleManager.getIntance().createTag(et_name.getText().toString(), membersList, new UserTagCallback() {
                        @Override
                        public void onBack(UserTags userTags) {
                            hideProgress();
                            Intent intent = new Intent();
                            intent.putExtra("usertag", userTags);
                            intent.putExtra("type", tagType);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                        }

                        @Override
                        public void onError() {
                            hideProgress();
                        }
                    });
                } else {
                    UserTags newUserTags = new UserTags(et_name.getText().toString(), membersList);
                    newUserTags.id = mUserTags.id;
                    UserCircleManager.getIntance().editUserTags(mUserTags, newUserTags, new UserTagCallback() {
                        @Override
                        public void onBack(UserTags userTags) {
                            hideProgress();
                            Intent intent = new Intent();
                            intent.putExtra("usertag", userTags);
                            intent.putExtra("type", tagType);
                            setResult(Activity.RESULT_OK, intent);
                            finish();
                        }

                        @Override
                        public void onError() {
                            hideProgress();
                        }
                    });

                }

            }
        });


        GridLayoutManager layoutManager = new GridLayoutManager(this, 5);
        layoutManager.setOrientation(GridLayoutManager.VERTICAL);
        recyclerView.setLayoutManager(layoutManager);
        userGridAdapter = new UserGridAdapter(membersList);
        recyclerView.setAdapter(userGridAdapter);
        userGridAdapter.setOnItemClickListener((adapter, view1, position) -> {
            UserInfo member = membersList.get(position);
            clickMember(member);
        });
        userGridAdapter.setOnItemChildClickListener(new OnItemChildClickListener() {
            @Override
            public void onItemChildClick(@NonNull @NotNull BaseQuickAdapter adapter, @NonNull @NotNull View view, int position) {
                UserInfo userInfo = userGridAdapter.getItem(position);
                if (view.getId() == R.id.delete_button) {
                    membersList.remove(userInfo);
                    userGridAdapter.notifyDataSetChanged();
                }
            }
        });
    }


    private final int REQUEST_USER_CODE = 2222;

    private void clickMember(UserInfo user) {
        if (user.isOptAdd()) {
            ArrayList<UserInfo> userInfos = new ArrayList<>();
            if (membersList != null && membersList.size() > 0) {
                userInfos.addAll(membersList);
                userInfos.remove(getAddUserInfo());
            }
            startActivityForResult(MobileContactHomeActivity.getActivityForResult(this, 3, userInfos), REQUEST_USER_CODE);
        } else {
            if (user.id == UserInfo.getUserInfo().id) {
                viewModel.startContainerActivity(PersonalDataFragment.class.getCanonicalName());
            } else {
                ContactDetailActivity.start(this, user);
            }
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_USER_CODE && data != null && data.getSerializableExtra("users") != null) {
            ArrayList<UserInfo> userInfos = (ArrayList<UserInfo>) data.getSerializableExtra("users");
            membersList.clear();
            membersList.addAll(userInfos);
            membersList.add(getAddUserInfo());
            userGridAdapter.notifyDataSetChanged();
        }
    }

    @Override
    protected boolean isHaveButterKnife() {
        return true;
    }

    @Override
    public int initContentView(Bundle savedInstanceState) {
        return R.layout.activity_user_tags;
    }

    @Override
    public int initVariableId() {
        return BR.viewModel;
    }
}
